<template>
  <!-- 面试技巧页面 -->
  <div class='container'>
    <el-card class="box-card">
     <!------------------------ 头部表单 ------------------------>
      <div>
        <el-form :inline="true" :model="lHead"  ref="lHead" size="mini">
          <el-form-item label="关键字" prop="keyword">
            <el-input  placeholder="根据文章标题搜索" v-model.trim="lHead.keyword"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-select placeholder="请选择" v-model="lHead.state">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="xReset">清空</el-button>
            <el-button type="primary" @click="xSeek"   v-loading='isLoading' >搜索</el-button>
          </el-form-item>
          <el-button
          class="xright"
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="xAdd">新增技巧
          </el-button>
        </el-form>
      </div>
      <!------------------------ 头部表单end ------------------------>
      <!------------------------ 数据显示条 ------------------------>
      <el-alert
        type="info"
        class="alert"
        :closable="false"
        show-icon>共{{counts}}条记录
      </el-alert>
      <!------------------------ 数据显示条end ------------------------>
      <!------------------------ 下部表格 ------------------------>
      <template>
        <el-table
          v-loading="isLoading"
          ref="singleTable"
          :data="tableData"
          highlight-current-row
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="100">
          </el-table-column>
          <el-table-column
            label="文章标题">
            <template slot-scope="scope">
              <div class="ltitle">{{scope.row.title}}</div>
              <el-button
                type="text"
                :class="{'el-icon-film': scope.row.videoURL}"
                @click="xVideo(scope.row.videoURL)">
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            property="visits"
            label="阅读数"
            width="100">
          </el-table-column>
          <el-table-column
            property="username"
            label="录入人"
            width="100">
          </el-table-column>
          <el-table-column
            label="录入时间"
            width="200">
            <template slot-scope="scope">
              <span>{{scope.row.createTime | parseTimeByString("{y}-{m}-{d} {h}:{m}:{s}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            property="state"
            label="状态"
            width="100">
            <template slot-scope="scope">
            <span v-if="scope.row.state === 1">已启用</span>
            <span v-else>已禁用</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            property="alter"
            label="操作"
            width="200">
            <template slot-scope="scope">
              <el-button type="text" @click="xPreview(scope.row.id)">预览</el-button>
              <el-button
              v-if="scope.row.state === 1"
              @click="xChangeState(scope.row.id, 0)" type="text" >禁用
              </el-button>
              <el-button
              v-if="scope.row.state === 0"
              @click="xChangeState(scope.row.id, 1)" type="text" >启用
              </el-button>
              <el-button v-if="scope.row.state === 0" @click="xAlter(scope.row)" type="text" >修改</el-button>
              <el-button disabled v-if="scope.row.state === 1" type="text" >修改</el-button>
              <el-button v-if="scope.row.state === 0" type="text" @click="xDelete(scope.row.id)">删除</el-button>
              <el-button disabled v-if="scope.row.state === 1" type="text" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!------------------------ 分页------------------------>
      <el-pagination
      @current-change="xCurrentChange"
      @size-change="xSizeChange"
      :current-page="placeArray.page"
      class="lright"
      background
      :disabled="isLoading"
      :page-sizes="[2, 5, 10, 20, 50]"
      :page-size="placeArray.pagesize"
      layout="prev, pager, next, sizes, jumper"
      :total="counts">
      </el-pagination>
      <!------------------------ 分页end ------------------------>
      <!------------------------ 下部表格end ------------------------>
      <!------------------------ 视频弹框 ------------------------>
      <div
      class="lcover"
      :style="protogenesis">
        <el-button
        @click="xCloseVideo"
        class="lbutton"
        type="info"
        circle>
        <p  class="el-icon-close licon"></p>
        </el-button>
        <video
        class="lbox"
        width="100%"
        height="100%"
        controls="controls"
        autoplay="autoplay"
        :src= "lurl">
        </video>
      </div>
      <!------------------------ 视频弹框end ------------------------>
      <!------------------------ 新增,修改 弹框------------------------>
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        v-if="dialogVisible"
        width="50%">
        <el-form :model="lruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="lruleForm.title" placeholder="请输入文章标题"></el-input>
          </el-form-item>
          <el-form-item label="文章正文" prop="articleBody">
            <quill-editor v-model="lruleForm.articleBody" :options="editorOption"></quill-editor>
          </el-form-item>
          <el-form-item label="视频地址" prop="videoURL">
            <el-input v-model="lruleForm.videoURL" placeholder="请输入视频地址"></el-input>
          </el-form-item>
            <el-form-item>
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" :isLoading ='isLoading'  @click="xConfirm('lruleForm')">确认</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!------------------------ 弹框end ------------------------>
      <!------------------------ 预览弹框 ------------------------>
      <el-dialog aria-modal="true" title="预览文章" :visible.sync="isPreview">
        <div>
          <h2>{{lruleForm.title}}</h2>
          <span style="margin-right: 8px">{{lTime}}</span>
          <span style="margin-right: 8px">{{lruleForm.creatorID === 1 ? '录入员': '超级管理员'}}</span>
          <span class="el-icon-view">{{lruleForm.visits}}</span>
          <p class="quill" v-html="lruleForm.articleBody"></p>
        </div>
      </el-dialog>
      <!------------------------ 预览弹框end ------------------------>
    </el-card>
  </div>
</template>

<script>
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入组件
import { quillEditor } from 'vue-quill-editor'
import { parseTimeByString } from '@/filters/index.js'
import { list, remove, changeState, add, update, detail } from '@/api/hmmm/articles.js'
export default {
  components: {
    quillEditor
  },
  name: 'articles',
  data () {
    return {
      timer: null, // 节流
      protogenesis: 'display:none',
      lTime: null,
      title: '',
      isPreview: false, // 预览 弹窗隐藏
      dialogVisible: false, // 新增修改 弹窗隐藏
      lurl: '', // 视频链接
      lvideo: false, // 视频弹框隐藏
      total: 0,
      counts: null,
      isLoading: false, // 加载状态
      tableData: [], // 存放请求回来的数值
      placeArray: {
        page: 1,
        pagesize: 10
      },
      lHead: {
        keyword: null,
        state: null
      },
      // 富文本配置对象
      editorOption: {
        // 占位配置
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      // 弹窗正则
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '请输入文章正文', trigger: 'blur' }
        ],
        videoURL: [
          { pattern: /^https?:\/\/(.+\/)+.+(\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4))$/i, message: '请输入正确视频地址' }
        ]
      },
      // 弹出框表单
      lruleForm: {
        id: null,
        title: null, // 标题
        articleBody: null, // 文章正文
        videoURL: null, // 视频地址
        createTime: null, // 录入时间
        state: null, // 状态
        visits: null, // 阅读量
        creatorID: null
      }
    }
  },
  mounted () {
    this.xSeek()
  },
  methods: {
    // 存
    buildParams () {
      return Object.assign({}, this.queryCondition, this.placeArray)
    },
    // 列表请求
    async xList () {
      const depositObj = this.buildParams()
      this.isLoading = true
      const { data: res } = await list(depositObj)
      this.counts = res.counts
      this.tableData = res.items
      this.isLoading = false
    },
    // 清除
    xReset () {
      this.$refs.lHead.resetFields()
    },
    // 用户点击了搜索按钮
    xSeek () {
      this.isLoading = true
      if (this.timer) return
      this.timer = setTimeout(() => {
        this.queryCondition = Object.assign({}, this.lHead)
        this.placeArray.page = 1
        this.xList()
        this.timer = null
      }, 2000)
      this.isLoading = false
    },
    // 页码大小
    xSizeChange (val) {
      this.placeArray.pagesize = val
      this.placeArray.page = 1
      this.xList()
    },
    // 当前页变动
    xCurrentChange (val) {
      this.placeArray.page = val
      this.xList()
    },
    // 删除xDelete功能内容存放
    async doDelete (id) {
      try {
        await remove({ id })
        this.$message.success('删除成功!')
        this.xList()
      } catch (err) {
        this.$message.error('删除失败!')
      }
    },
    // 删除功能
    xDelete (id) {
      this.$confirm('此操作将永久删除 ' + ', 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.doDelete(id)
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    // 禁用 启用
    async xChangeState (id, state) {
      try {
        const res = await changeState({ id, state })
        this.$message.success('操作成功')
        this.xList()
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    // 视频播放
    xVideo (video) {
      this.protogenesis = 'display:block'
      this.lurl = video
    },
    // 视频隐藏,清空视频
    xCloseVideo () {
      this.protogenesis = 'display:none'
      this.lurl = ''
    },
    // 清空ruleForm
    closeRuleForm () {
      this.lruleForm.id = null
      this.lruleForm.title = null
      this.lruleForm.videoURL = null
      this.lruleForm.articleBody = null
    },
    // 预览
    xPreview (id) {
      this.isPreview = true
      this.getArt(id)
    },
    // 新增文章
    async xAdd () {
      this.title = '新增文章'
      this.closeRuleForm()
      this.dialogVisible = true
    },
    // 获取文章详情
    async getArt (id) {
      try {
        const res = await detail({ id })
        this.lruleForm = res.data
        this.lTime = parseTimeByString(res.data.createTime)
        console.log(this.datee)
      } catch (err) {
        console.log(err)
      }
    },
    // 编辑文章
    async xAlter (row) {
      this.title = '修改文章'
      this.dialogVisible = true
      this.getArt(row.id)
    },
    // 添加/编辑发布
    async xAddEdit () {
      const id = this.lruleForm.id
      const { title, articleBody, videoURL } = this.lruleForm
      const data = {
        id: id,
        title: title,
        articleBody: articleBody,
        videoURL: videoURL
      }
      // console.log(data)
      if (id) {
        // 修改文章
        try {
          await update(data)
          this.xList()
          this.$message.success('修改成功')
          this.dialogVisible = false
        } catch (err) {
          console.log(err)
          this.$message.error('修改失败')
        }
      } else {
        // 添加文章
        try {
          await add(data)
          this.xList()
          this.$message.success('添加成功')
          this.dialogVisible = false
        } catch (err) {
          console.log(err)
          this.$message.error('添加失败')
        }
      }
    },
    // 添加/修改文章
    async xConfirm (ruleForm) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.isLoading = true
          this.xAddEdit()
          this.placeArray.page = 1
          this.isLoading = false
        } else {
          this.isLoading = false
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.container{
  padding: 20px;
}
.xright{
  float: right;
}
.box-card{
  padding: 20px;
}
.alert {
  margin: 10px 0px;
}
.lright{
  float: right;
}
.ltitle{
  display: inline-block;
}
.quill {
  margin-top: 10px;
  background-color: #f5f5f5;
}
.lcover{
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.3);
  overflow: hidden;
  z-index: 9999;
}
.lbutton {
    z-index:999;
    width: 50px;
    height: 50px;
    position: absolute;
    top: 30px;
    left: 50%;
    -webkit-transform: translate(-50%);
    transform: translate(-50%);
    background: rgba(0,0,0,.4);
    -webkit-box-shadow: 0 0 5px rgba(0,0,0,.4);
    box-shadow: 0 0 5px rgba(0,0,0,.4);
    border-radius: 50%;
    text-align: center;
    line-height: 50px;
    color: #eff30b;
    font-size: 30px;
}
.lbox{
  width: 600px;
  height: 500px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}
.licon{
    font-size: 45px;
    margin-top: -5px;
    margin-left: -8px;
}
::v-deep .ql-editor  {
  min-height: 200px;
}
::v-deep .ql-align-center img {
  width: 100%;
}
</style>
